/**
 * @description table 页面操作方法封装
 * @param apiUrl 获取表格数据 ApiUrl(必传)
 * @param initParam 获取数据初始化参数(不必传，默认为{})
 * @param isPageable 是否有分页(不必传，默认为true)
 * @param tableRef 当前表格的DOM(不必传，默认为“”)
 * @param 当前页面 name(做分页缓存)
 * */
export const useTable = (apiUrl, initParam, isPageable, tableRef, name) => {
	const txt = name + '-page';
	let size = 10;
	if (sessionStorage.getItem(txt)) {
		size = Number(sessionStorage.getItem(txt));
	}
	const state = reactive({
		// 表格数据
		tableData: [],
		// 表格外部数据
		moreData: {},
		// 是否展开更多搜索框
		searchShow: false,
		// 分页数据
		pageable: {
			// 当前页数
			current: 1,
			// 每页显示条数
			size,
			// 总条数
			total: 0
		},
		// 查询参数(只包括查询)
		searchParam: {},
		// 初始化默认的查询参数
		initSearchParam: {},
		// 总参数(包含分页和查询参数)
		totalParam: {},
		// 加载
		loading: false
	});

	/**
	 * @description 分页查询数据(只包括分页和表格字段排序,其他排序方式可自行配置)
	 * */
	const pageParam = computed({
		get: () => {
			return {
				current: state.pageable.current,
				size: state.pageable.size
			};
		},
		set: (newVal) => {
		}
	});

	/**
	 * @description 获取表格数据
	 * @return void
	 * */
	const getTableList = async (isTime) => {
		try {
			// 更新查询参数
			updatedTotalParam();
			Object.assign(state.totalParam, initParam);
			const query = JSON.parse(JSON.stringify(state.totalParam));
			if (query.period) {
				query.startTime = query.period[0];
				query.endTime = query.period[1];
				delete query.period
			}
			if (!isTime) state.loading = true;
			let res = await apiUrl(query);
			const tableList = res.data.list.length ? res.data.list : [];
			state.tableData = isPageable ? tableList : [];
			if (res.data.data) {
				state.moreData = {
					...res.data
				}
				delete state.moreData.data
			}
			// // 解构后台返回的分页数据(如果有分页更新分页信息)
			const { current, size, total } = res.data;
			state.loading = false;
			isPageable && updatePageable({ current: Number(current), size: Number(size), total: Number(total) });
		} catch (error) {
		}
	};

	/**
	 * @description 更新查询参数
	 * @return void
	 * */
	const updatedTotalParam = () => {
		state.totalParam = {};
		let nowSearchParam = {};
		// 防止手动清空输入框携带参数（可以自定义查询参数前缀）
		for (let key in state.searchParam) {
			// * 某些情况下参数为 false/0 也应该携带参数
			if (state.searchParam[key] || state.searchParam[key] === false || state.searchParam[key] === 0) {
				nowSearchParam[key] = state.searchParam[key];
			}
		}
		Object.assign(state.totalParam, nowSearchParam, isPageable ? pageParam.value : {});
	};

	/**
	 * @description 更新分页信息
	 * @param resPageable 后台返回的分页数据
	 * @return void
	 * */
	const updatePageable = (resPageable) => {
		Object.assign(state.pageable, resPageable);
	};

	/**
	 * @description 表格数据查询
	 * @return void
	 * */
	const search = () => {
		state.pageable.current = 1;
		tableRef.value.clearSelection();
		getTableList();
	};

	/**
	 * @description 表格数据重置
	 * @return void
	 * */
	const reset = () => {
		state.pageable.current = 1;
		state.searchParam = {};
		// 重置搜索表单的时，如果有默认搜索参数，则重置默认的搜索参数
		Object.keys(state.initSearchParam).forEach(key => {
			state.searchParam[key] = state.initSearchParam[key];
		});
		tableRef.value.clearSelection();
		getTableList();
	};
	/*
	*@description 分页改变
	@param val { current: number, size: number }
	@return void
	*/
	const getPagination = (val) => {
		state.pageable.current = val.current;
		state.pageable.size = val.size;
		sessionStorage.setItem(txt, val.size + '');
		getTableList();
	}
	return {
		...toRefs(state),
		getTableList,
		search,
		reset,
		getPagination
	};
};
